<template>
  <div v-loading="isLoading" class="detail-container">
    <Layout>
      <div class="main-content" ref="mainContent">
        <BlogDetail :blog="data" />
        <BlogComment v-if="!isLoading" />
      </div>
      <template slot="right">
        <BlogToc :contents="data.toc" />
      </template>
    </Layout>
    <BackTop @click="handlerBackTop" v-show="scrollTopNum > 1600" />
  </div>
</template>

<script>
import { getBlogDetail } from "@/api/blog.js";
import fetchData from "@/mixins/fetchData.js";
import { BlogDetail, BlogToc, BlogComment } from "@/views/Blog/components";
import Layout from "@/components/Layout";
import BackTop from "@/components/BackTop";
import { setRouterTitle } from "@/utils/setTitleController";
export default {
  name: "Detail",
  components: {
    Layout,
    BlogDetail,
    BlogToc,
    BlogComment,
    BackTop,
  },
  mixins: [fetchData({})],
  mounted() {
    this.$refs.mainContent.addEventListener(
      "scroll",
      this.handlerScrollMainContent
    );
  },
  destroyed() {
    this.$refs.mainContent?.removeEventListener(
      "scroll",
      this.handlerScrollMainContent
    );
  },
  updated() {
    const old_hash = location.hash;
    location.hash = "";
    setTimeout(() => {
      location.hash = old_hash;
    }, 50);
  },
  data() {
    return {
      scrollTopNum: 0,
    };
  },
  methods: {
    async fetchData() {
      const { id } = this.$route.params;
      let res = await getBlogDetail(id);
      if (!res) {
        this.$router.push({ name: "NotFound" });
        return {};
      }
      setRouterTitle(res?.data?.title || "");
      return res?.data || {};
    },
    handlerScrollMainContent() {
      this.scrollTopNum = this.$refs.mainContent.scrollTop;
      this.$eventBus.$emit("mainScroll", this.$refs.mainContent);
    },
    handlerBackTop() {
      location.hash = "#";
      this.$refs.mainContent.scrollTop = 0;
    },
  },
};
</script>

<style scoped lang="less">
@import "@/styles/var.less";
.detail-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .main-content {
    scroll-behavior: smooth;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 5px 15px;
    box-sizing: border-box;
  }
}
</style>
